//
//  ProfilView.m
//  VivaModa
//
//  Created by Sergey on 3/2/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "ProfilView.h"
#import "profil_cell.h"
#import "InviteAlert.h"



@interface ProfilView (){
    UIBarButtonItem *edit_profil;
    NSArray *array_custom_data;
}
@property(nonatomic,retain) UILabel *title_label;
@end

@implementation ProfilView
@synthesize tableView;
@synthesize title_label;
@synthesize editProfilView;
@synthesize statisticsView;
@synthesize connection_invite_friend;
@synthesize inviteData;

@synthesize balansData;
@synthesize connection_balans;
@synthesize needReload;

NSString *balance = @"1.00 рубл.";


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    self.title_label.text = [NSString stringWithFormat:@"Личный кабинет, \n %@ !",[Singleton sharedMySingleton].user_name];
    if (self.needReload) {
        [self getBalanceFromServer];
        self.needReload = NO;
    }
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    
    [self addCustomBackButton];
    
    //edit_profil = [[UIBarButtonItem alloc] initWithTitle:@" Редактировать " style:UIBarButtonItemStylePlain target:self action:@selector(switchEditProfil)];
    //self.navigationItem.rightBarButtonItem = edit_profil;
    
    
    UIButton *edit_pro = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 110, 29)];
    [edit_pro setBackgroundImage:[[UIImage imageNamed:@"nav_btn_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [edit_pro setTitle:@" Редактировать " forState:UIControlStateNormal];
    [edit_pro.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [edit_pro setShowsTouchWhenHighlighted:NO];
    [edit_pro addTarget:self action:@selector(switchEditProfil) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *edit_b = [[UIBarButtonItem alloc] initWithCustomView:edit_pro];
    self.navigationItem.rightBarButtonItem = edit_b;
    
    
    
    
    
    
    
    
    
    
    
    
    self.title_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    self.title_label.backgroundColor = [UIColor clearColor];
    self.title_label.font = [UIFont fontWithName:@"Arial" size:12];
    self.title_label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    self.title_label.textAlignment = UITextAlignmentCenter;
    self.title_label.textColor = [UIColor whiteColor]; // change this color
    self.title_label.numberOfLines = 2;
    
    //self.label.text = [self.navigationItem title];
    
    self.navigationItem.titleView = self.title_label;
    
    
    
    
    array_custom_data = @[
    @{@"name_title":@"Ваш баланс",@"body_text":@"",@"description_text":@"С каждой Вашей покупки Вам будет начисляться 3% на ваш личный счет.\nБонусные рубли Вы можете использовать при оформлении покупки"},
    @{@"name_title":@"Статистика Вашего баланса",@"body_text":@"НАКОПИТЕЛЬНЫЕ БОНУСЫ С ВАШИХ ПОКУПОК И ПОКУПОК ВАШИХ ДРУЗЕЙ",@"description_text":@""},
    @{@"name_title":@"Статистика Ваших покупок",@"body_text":@"НАКОПИТЕЛЬНЫЕ БОНУСЫ С ВАШИХ ПОКУПОК",@"description_text":@"С каждой Вашей покупки Вам будет начисляться 3% на ваш личный счет."},
    @{@"name_title":@"Статистика покупок друзей",@"body_text":@"НАКОПИТЕЛЬНЫЕ БОНУСЫ С ПОКУПОК ВАШИХ ДРУЗЕЙ",@"description_text":@"С каждой покупки всех Ваших друзей Вам будет начисляться 3% в течении года с момента первой покупки."},
    @{@"name_title":@"Пригласить подруг или друзей",@"body_text":@"",@"description_text":@"С каждой покупки всех Ваших друзей Вам будет начисляться 3% в течении года с момента первой покупки."}
    ];
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array_custom_data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"register_cell";
    
    
    
    profil_cell *cell = nil;
    cell = (profil_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"profil_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[profil_cell class]])
            {
                cell = (profil_cell *)currentObject;
                break;
            }
        }
    }
    
    
    [cell.name_title setFont:[UIFont fontWithName:@"Century Gothic" size:16.0]];
    [cell.name_body setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:15]];
    [cell.name_description setFont:[UIFont fontWithName:@"Verdana" size:12]];
    
    cell.name_title.text = [[array_custom_data objectAtIndex:indexPath.row] objectForKey:@"name_title"];
    cell.name_body.text = [[array_custom_data objectAtIndex:indexPath.row] objectForKey:@"body_text"];
    cell.name_description.text = [[array_custom_data objectAtIndex:indexPath.row] objectForKey:@"description_text"];
    
    switch (indexPath.row) {
        case 0:{
            cell.name_description.frame = CGRectMake(cell.name_description.frame.origin.x, cell.name_description.frame.origin.y-20, cell.name_description.frame.size.width, cell.name_description.frame.size.height+30);
            cell.name_body.text = balance;
            cell.name_body.textAlignment = UITextAlignmentCenter;
            cell.name_body.frame = CGRectOffset(cell.name_body.frame, 0, -10);
            cell.selectionStyle = UITableViewCellEditingStyleNone;
            break;}
        case 1:{
           cell.name_body.frame = CGRectMake(cell.name_body.frame.origin.x, cell.name_body.frame.origin.y-12, cell.name_body.frame.size.width, cell.name_body.frame.size.height+40);
            break;}
        case 2:{
            
            break;}
        case 3:{
            cell.name_description.frame = CGRectOffset(cell.name_description.frame, 0, 7);
            break;}
        case 4:{
            cell.name_description.frame = CGRectOffset(cell.name_description.frame, 0, -45);
            break;}
        default:
            break;
    }
    
    
    UIView *vbg = [[UIView alloc] init];
    vbg.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = vbg;
    
    
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:{
            return 130;
            break;}
        case 1:{
            return 104;
            break;}
        case 2:{
            return 124;
            break;}
        case 3:{
            return 134;
            break;}
        case 4:{
            return 82;
            break;}
        default:
            break;
    }

    return 124;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row) {
        case 0:{
            return;
            break;}
        case 1:{
            if (!statisticsView) {
                statisticsView = [[StatisticsView alloc] initWithNibName:@"StatisticsView" bundle:nil];
            }
            statisticsView.title_name = [[array_custom_data objectAtIndex:indexPath.row] objectForKey:@"name_title"];
            statisticsView.statisticsType = statistic_my_balans;
            statisticsView.needReload = YES;
            [self.navigationController pushViewController:statisticsView animated:YES];
            break;}
        case 2:{
            if (!statisticsView) {
                statisticsView = [[StatisticsView alloc] initWithNibName:@"StatisticsView" bundle:nil];
            }
            statisticsView.title_name = [[array_custom_data objectAtIndex:indexPath.row] objectForKey:@"name_title"];
            statisticsView.statisticsType = statistic_my_purchace;
            statisticsView.needReload = YES;
            [self.navigationController pushViewController:statisticsView animated:YES];
            break;}
        case 3:{
            if (!statisticsView) {
                statisticsView = [[StatisticsView alloc] initWithNibName:@"StatisticsView" bundle:nil];
            }
            statisticsView.title_name = [[array_custom_data objectAtIndex:indexPath.row] objectForKey:@"name_title"];
            statisticsView.statisticsType = statistic_my_friend;
            statisticsView.needReload = YES;
            [self.navigationController pushViewController:statisticsView animated:YES];
            break;}
        case 4:{
            InviteAlert *loginPrompt = [[InviteAlert alloc] initWithTitle:@"Добавить друга" delegate:self cancelButtonTitle:@"Отмена" otherButtonTitle:@"Добавить"];
            [InviteAlert setBackgroundColor:[UIColor colorWithRed:39.0/255 green:38.0/255 blue:37.0/255 alpha:1]
                            withStrokeColor:[UIColor blackColor]];
            [loginPrompt show];
            break;}
        default:
            break;
    }
    
   
}

- (void)didPresentAlertView:(UIAlertView *)alertView {
	if ([alertView isKindOfClass:[InviteAlert class]]) {
		InviteAlert *inviteUser = (InviteAlert *)alertView;
		[inviteUser.plainTextField becomeFirstResponder];
		[inviteUser setNeedsLayout];
	}
}


-(void)switchEditProfil{
    if (!editProfilView) {
        editProfilView = [[EditProfilView alloc] initWithNibName:@"EditProfilView" bundle:nil];
    }
    editProfilView.needReload = YES;
    [self.navigationController pushViewController:editProfilView animated:YES];
}




- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex == [alertView cancelButtonIndex]) {
	} else {
		if ([alertView isKindOfClass:[InviteAlert class]]) {
			InviteAlert *loginPrompt = (InviteAlert *)alertView;
		    //NSLog(@"invite user email - %@", loginPrompt.plainTextField.text);
            
            NSString *email_friend = loginPrompt.plainTextField.text;
            
            //NSLog(@"user id = %i",[Singleton sharedMySingleton].user_id);
            
            
            if ([email_friend length]>7) {
                NSString* params = [NSString stringWithFormat:@"email_friend=%@&id_customer=%i",email_friend,[Singleton sharedMySingleton].user_id]; // задаем параметры POST запроса
                
                NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/invite_friend.php"]; // куда отправлять
                NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
                request.HTTPMethod = @"POST";
                request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
                
                connection_invite_friend = [NSURLConnection connectionWithRequest:request delegate:self];
                [self displayActivityView];
                if (connection_invite_friend) {
                    self.inviteData = [NSMutableData data];
                }
            }else{
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Не правильно введен email адресс"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                [alert show];
            }
            
     	}
	}
}




- (void)getBalanceFromServer{
    NSString* params = [NSString stringWithFormat:@"id_customer=%i",[Singleton sharedMySingleton].user_id]; // задаем параметры POST запроса
    
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/balans.php"]; // куда отправлять
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
    
    connection_balans = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_balans) {
        self.balansData = [NSMutableData data];
    }

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection == connection_invite_friend) {
        [inviteData appendData:data];
    }else{
        if (connection == connection_balans) {
            [balansData appendData:data];
        }
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (connection == connection_invite_friend) {
        //NSString *result = [[NSString alloc] initWithData:userData encoding:NSUTF8StringEncoding];
        [self parseJSON:inviteData urlConnection:connection_invite_friend];
    }else{
        if (connection == connection_balans) {
            [self parseJSON:balansData urlConnection:connection_balans];
        }
    }
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data urlConnection:(NSURLConnection*)connection{
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    NSString* requestResult = [json objectForKey:@"success"];
    NSString * message = [json objectForKey:@"message"];
    //NSLog(@"json = %@",json);
    
    
    if (connection == connection_invite_friend) {
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:message];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        }];
        [alert show];

    }else{
        if (connection == connection_balans) {
            if ([requestResult integerValue] == 1) {
                balance = [NSString stringWithFormat:@"%@ рубл.",message];
                [self.tableView reloadData];
            }else{
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации баланса"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                [alert show];
            }
        }else{
            
        }
    }
    
    
    [self removeActivityView];
    
}


- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}

#pragma mark Dejal activity

- (void)displayActivityView
{
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark

-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}


-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Назад" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
